package pers.vic.sso.server.storage;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import pers.vic.boot.util.JsonUtil;
import pers.vic.sso.server.constant.SsoServerConstant;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 描述:
 *      redis存储策略
 * @author Vic.xu
 * @date 2021-11-08 9:42
 */
@Component
@ConditionalOnProperty(name = SsoServerConstant.STORAGE_STRATEGY, havingValue = SsoServerConstant.REDIS_MANAGER)
//@ConditionalOnBean(StringRedisTemplate.class)
public class RedisStorageStrategy<T> implements StorageStrategy<T>{

    private Logger logger = LoggerFactory.getLogger(RedisStorageStrategy.class);

    private static String redis_prefix = "sso-server:";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private String getKey(String cacheName, String key){
        return redis_prefix + cacheName + ":" + key;
    }

    @Override
    public void storage(String cacheName, String key, T data, int expire) {
        String text = JsonUtil.toJson(data);
        stringRedisTemplate.opsForValue().set(getKey(cacheName, key), text, expire, TimeUnit.SECONDS);
    }

    @Override
    public T getData(String cacheName, String key,Class<T> clazz) {
        String text = stringRedisTemplate.opsForValue().get(getKey(cacheName, key));
        if (StringUtils.isEmpty(text)) {
            return null;
        }
        T data = JsonUtil.jsonToObject(text, clazz);
        return data;
    }

    @Override
    public T refresh(String cacheName, String key, int expire,Class<T> clazz) {
        T data = getData(cacheName, key, clazz);
        if (data == null) {
            return null;
        }
        stringRedisTemplate.expire(getKey(cacheName, key), expire, TimeUnit.SECONDS);
        return data;
    }

    @Override
    public T remove(String cacheName, String key, Class<T> clazz) {
        String text = stringRedisTemplate.opsForValue().get(getKey(cacheName, key));
        if (StringUtils.isEmpty(text)) {
            return null;
        }
        stringRedisTemplate.delete(getKey(cacheName, key));
        T data = JsonUtil.jsonToObject(text, clazz);
        return data;
    }

    @Override
    public void storage2SetData(String cacheName, String key, String data) {
        stringRedisTemplate.opsForSet().add(getKey(cacheName, key), data);
    }

    @Override
    public Set<String> getSetData(String cacheName, String key) {
        Set<String> accessTokenSet = stringRedisTemplate.opsForSet().members(getKey(cacheName, key));
       return accessTokenSet;
    }

    @Override
    public void cleanSchedule() {
        //tgt 不存在的时候 删除对应的 accessToken
    }
}
